package com.junt.avplayer;

import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class NEPlayer implements SurfaceHolder.Callback {
    static {
        System.loadLibrary("avplayer");
    }

    private String dataSource;
    private SurfaceHolder holder;


    public void setDataSource(String dataSource) {
        this.dataSource = dataSource;
    }


    public void setSurfaceView(SurfaceView surfaceView) {
        if (null != holder) {
            holder.removeCallback(this);
        }
        holder = surfaceView.getHolder();
        holder.addCallback(this);
    }


    /**
     * 准备资源
     */
    public void prepare() {
        prepareNative(dataSource);
    }

    /**
     * java-->native
     *
     * @param dataSource 资源路径
     */
    private native void prepareNative(String dataSource);

    /**
     * java-->native
     * 开始播放
     */
    public void start() {
        startNative();
    }

    private native void startNative();


    /**
     * native-->java
     * 供native反射调用
     * 表示播放器准备完毕
     */
    public void onPrepared() {
        if (onCallBackListener != null) {
            onCallBackListener.onPrepared();
        }
    }


    /**
     * native-->java
     * 供native反射调用
     * 表示错误
     */
    public void onError(int errorCode) {
        final int code = errorCode;
        if (onCallBackListener != null) {
            onCallBackListener.onError(code);
        }
    }


    @Override
    public void surfaceCreated(SurfaceHolder holder) {

    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        setSurfaceNative(holder.getSurface());
    }

    private native void setSurfaceNative(Surface surface);

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {

    }


    private OnCallBackListener onCallBackListener;

    public void setOnCallBackListener(OnCallBackListener onCallBackListener) {
        this.onCallBackListener = onCallBackListener;
    }

    interface OnCallBackListener {
        void onError(int errorCode);

        void onPrepared();
    }
}
